{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ac3941e6",
   "metadata": {},
   "source": [
    "# Text Subject & Urdu Translation Assistant\n",
    "\n",
    "This notebook helps you convert English text into an email-ready subject, a concise summary, and two Urdu renditions (everyday spoken and refined/formal) written in Perso‑Arabic script (اردو). It is designed to be reusable and easy to adapt for others in a public repository.\n",
    "\n",
    "What this notebook produces:\n",
    "- Suggested email subject (English)\n",
    "- Short summary (English)\n",
    "- Everyday / colloquial Urdu translations (Perso‑Arabic script)\n",
    "- Refined / formal Urdu translations (Perso‑Arabic script)\n",
    "\n",
    "Why use this:\n",
    "- Quickly generate subject lines and human-readable summaries for long English passages.\n",
    "- Produce Urdu outputs that use native script (not romanization), with both casual and formal variants.\n",
    "- Useful for writers, localization, email automation, and language learning.\n",
    "\n",
    "How it works (high level):\n",
    "1. Paste or edit the English input in the `user_prompt` cell.\n",
    "2. The notebook composes a system prompt that enforces output structure and Urdu script requirements.\n",
    "3. It calls the OpenAI chat API to generate the outputs in Markdown.\n",
    "4. The notebook post‑processes and renders the model response as formatted Markdown.\n",
    "\n",
    "Quick setup:\n",
    "- Ensure `OPENAI_API_KEY` is available in your environment (use a `.env` file or export it in your shell).\n",
    "- Install dependencies from `requirements.txt` (e.g.   `pip install -r requirements.txt`).\n",
    "\n",
    "Notes and best practices:\n",
    "- Do NOT commit API keys to the repository; use environment variables or CI secrets.\n",
    "- If the model returns romanized Urdu instead of Perso‑Arabic script, strengthen the system prompt to explicitly require Urdu script (this notebook already does this).\n",
    "- You can adapt the prompts or model parameters to change tone, length, or formality.\n",
    "\n",
    "Example input (already included in this notebook):\n",
    "\"Our children are not your children...\" — run the next cell to see subject, summary, and Urdu variants."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e735c365",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from IPython.display import Markdown, display\n",
    "from openai import OpenAI\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ca1fdf7",
   "metadata": {},
   "outputs": [],
   "source": [
    "load_dotenv(override=True)\n",
    "api_key = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "# Check the key\n",
    "\n",
    "if not api_key:\n",
    "    print(\"No API key was found - please head over to the troubleshooting notebook in this folder to identify & fix!\")\n",
    "elif not api_key.startswith(\"sk-proj-\"):\n",
    "    print(\"An API key was found, but it doesn't start sk-proj-; please check you're using the right key - see troubleshooting notebook\")\n",
    "elif api_key.strip() != api_key:\n",
    "    print(\"An API key was found, but it looks like it might have space or tab characters at the start or end - please remove them - see troubleshooting notebook\")\n",
    "else:\n",
    "    print(\"API key found and looks good so far!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "154cd713",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Step 1: Create your prompts\n",
    "\n",
    "system_prompt = \"\"\"\n",
    "You are a helpful assistant. Whenever the user requests Urdu, always RESPOND IN URDU USING THE PERSO-ARABIC SCRIPT (اردو). Do NOT use Latin letters or transliteration.\n",
    "\n",
    "Output requirements:\n",
    "- Use colloquial, everyday spoken Urdu (informal but polite) written in Perso-Arabic script.\n",
    "- Do NOT romanize (do NOT return words like \"salaam\" — write \"سلام\" instead).\n",
    "- Structure the response as Markdown with these sections (exact headings):\n",
    "  1. Suggested subject\n",
    "  2. Summary\n",
    "  3. Original text\n",
    "  4. Urdu translation (heading: \"اردو:\")\n",
    "- First give complete response in english (suggested subject, summary, original text) \n",
    "followed by urdu every day spoken (suggested subject, summart, original text), \n",
    "followed by nice, refine, elite urdu (uggested subject, summart, original text). \n",
    "Urdu response should have headings in urdu too\n",
    "\n",
    "\n",
    "Example enforcement: If asked to translate \"Hello\" -> output: \"سلام\" (NOT \"salaam\").\n",
    "\n",
    "Respond ONLY with the Markdown (no surrounding code fences). Use blank lines between paragraphs so the Markdown displays correctly.\n",
    "\"\"\"\n",
    "\n",
    "user_prompt = \"\"\"\n",
    "our children are not your children. They are the sons and daughters of Life's longing for itself. \n",
    "They come through you but not from you, And though they are with you yet they belong not to you.\n",
    "\n",
    "You may give them your love but not your thoughts, For they have their own thoughts. \n",
    "You may house their bodies but not their souls, For their souls dwell in the house of tomorrow, which you cannot visit, not even in your dreams. You may strive to be like them, but seek not to make them like you.\n",
    "\n",
    "For life goes not backward nor tarries with yesterday.\n",
    "\n",
    "You are the bows from which your children as living arrows are sent forth. \n",
    "The archer sees the mark upon the path of the infinite, and He bends you with His might that His arrows may go swift and far. \n",
    "Let your bending in the archer's hand be for gladness; For even as He loves the arrow that flies, so He loves also the bow that is stable.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d52a3105",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Step 2: Make the messages list\n",
    "messages = [\n",
    "    {\"role\": \"system\", \"content\": system_prompt},\n",
    "    {\"role\": \"user\", \"content\": user_prompt}\n",
    "]\n",
    "\n",
    "\n",
    "\n",
    "# Step 3: Call OpenAI\n",
    "# instantiate the client with the API key if available (new-style client)\n",
    "client = OpenAI(api_key=api_key) if api_key else OpenAI()\n",
    "response = client.chat.completions.create(model=\"gpt-4.1-nano\", messages=messages)\n",
    "content = response.choices[0].message.content\n",
    "\n",
    "# Step 4: normalize escaped sequences and display as Markdown\n",
    "print('repr(content):', repr(content))\n",
    "# If the model returned escaped unicode (e.g. '\\u0627') or literal backslash-n sequences, decode/unescape them\n",
    "try:\n",
    "    # First try to decode unicode escape sequences (\\uXXXX -> actual characters)\n",
    "    if '\\\\u' in content or '\\\\U' in content:\n",
    "        content = bytes(content, 'utf-8').decode('unicode_escape')\n",
    "    # Then normalize literal backslash-n sequences to real newlines\n",
    "    content = content.replace('\\\\\\\\n', '\\\\n').replace('\\\\n', '\\n').replace('\\\\\\n', '\\n')\n",
    "except Exception as e:\n",
    "    # If something goes wrong, at least replace common escaped newlines\n",
    "    content = content.replace('\\\\\\\\n', '\\\\n').replace('\\\\n', '\\n')\n",
    "\n",
    "display(Markdown(content))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llm-engineering",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
